package com.example.demo03_mvm.view;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModelProvider;

import com.example.demo03_mvm.R;
import com.example.demo03_mvm.viewmodel.BaseViewModel;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class BaseActivity<VM extends BaseViewModel,DB extends ViewDataBinding> extends AppCompatActivity {

    protected VM vm;
    protected DB db;
    protected abstract int inflateLayout();
    protected abstract void initData();
    protected abstract void initView();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //获取databinding
        db= DataBindingUtil.setContentView(this, inflateLayout());
        createViewModel();
        initView();
        initData();
    }

    public void createViewModel(){
        if(vm==null){
            Class mClass;
            Type type = getClass().getGenericSuperclass();
            if(type instanceof ParameterizedType){
                mClass=(Class) ((ParameterizedType)type).getActualTypeArguments()[0];
            }else{
                mClass=BaseViewModel.class;
            }
            vm=(VM) new ViewModelProvider(this).get(mClass);
        }
    }
}
